package airthmetic.exercise.queue;

public class _641_设计循环双端队列 {
    static class MyCircularDeque {
        private int capacity;
        private int[] elements;
        private int front;
        private int rear;
        public MyCircularDeque(int k) {
            this.capacity = k + 1;
            this.elements = new int[capacity];
            this.front = 0;
            this.rear = 0;
        }

        public boolean insertFront(int value) {
            if(isFull()){
                return false;
            }
            int index = (front - 1 + capacity) % capacity;
            elements[index] = value;
            front = index;
            return true;
        }

        public boolean insertLast(int value) {
            if(isFull()){
                return false;
            }
            elements[rear] = value;
            rear = (rear + 1) % capacity;
            return true;
        }

        public boolean deleteFront() {
            if(isEmpty()){
                return false;
            }
            front = (front + 1) % capacity;
            return true;
        }

        public boolean deleteLast() {
            if(isEmpty()){
                return false;
            }
            rear = (rear - 1 + capacity) % capacity;
            return true;
        }

        public int getFront() {
            if(isEmpty()){
                return -1;
            }
            return elements[front];
        }

        public int getRear() {
            if(isEmpty()){
                return -1;
            }
            int index = (rear - 1 + capacity) % capacity;
            return elements[index];
        }

        public boolean isEmpty() {
            return rear == front;
        }

        public boolean isFull() {
            return (rear + 1) % capacity == front;
        }
    }


    public static void main(String[] args) {
        MyCircularDeque queue = new MyCircularDeque(10);
        queue.insertLast(1);
        queue.insertLast(2);
        queue.insertFront(3);
        queue.insertFront(4);


        int front = queue.getRear();
        System.out.println(front);
        boolean full = queue.isFull();
        System.out.println(full);

        queue.deleteLast();
        queue.insertFront(4);
        System.out.println(queue.getFront());

    }
}
